#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Python基础：文件操作
"""

def write_to_file():
    """写入文件示例"""
    print("=== 写入文件示例 ===")
    # 写入文本文件
    with open("example.txt", "w", encoding="utf-8") as f:
        f.write("这是第一行\n")
        f.write("这是第二行\n")
        f.write("这是第三行\n")
    
    print("已创建 example.txt 文件")

def read_from_file():
    """读取文件示例"""
    print("\n=== 读取文件示例 ===")
    try:
        # 读取整个文件
        with open("example.txt", "r", encoding="utf-8") as f:
            content = f.read()
            print("读取整个文件:")
            print(content)
        
        # 按行读取
        with open("example.txt", "r", encoding="utf-8") as f:
            print("按行读取:")
            for line_num, line in enumerate(f, 1):
                print(f"  第{line_num}行: {line.strip()}")
        
        # 读取所有行到列表
        with open("example.txt", "r", encoding="utf-8") as f:
            lines = f.readlines()
            print(f"文件共有 {len(lines)} 行")
            
    except FileNotFoundError:
        print("文件未找到!")

def append_to_file():
    """追加到文件示例"""
    print("\n=== 追加到文件示例 ===")
    with open("example.txt", "a", encoding="utf-8") as f:
        f.write("这是追加的一行\n")
        f.write("这是另一行追加内容\n")
    
    print("已向 example.txt 文件追加内容")

def process_csv_data():
    """处理CSV数据示例"""
    print("\n=== CSV数据处理示例 ===")
    # 创建示例CSV数据
    csv_data = """姓名,年龄,城市,职业
张三,25,北京,工程师
李四,30,上海,设计师
王五,28,广州,教师
赵六,35,深圳,医生"""
    
    with open("employees.csv", "w", encoding="utf-8") as f:
        f.write(csv_data)
    
    # 读取并处理CSV数据
    employees = []
    with open("employees.csv", "r", encoding="utf-8") as f:
        header = f.readline().strip().split(",")
        print(f"表头: {header}")
        
        for line in f:
            data = line.strip().split(",")
            employee = dict(zip(header, data))
            employees.append(employee)
    
    print("员工信息:")
    for emp in employees:
        print(f"  {emp}")

def file_operations_summary():
    """文件操作总结"""
    print("\n=== 文件操作总结 ===")
    print("1. 使用 with 语句自动管理文件资源")
    print("2. 注意指定正确的编码格式(如 utf-8)")
    print("3. 读取模式: 'r', 写入模式: 'w', 追加模式: 'a'")
    print("4. 二进制模式: 'rb', 'wb'")
    print("5. 处理文件时要捕获可能的异常")

if __name__ == "__main__":
    write_to_file()
    read_from_file()
    append_to_file()
    read_from_file()  # 再次读取查看追加效果
    process_csv_data()
    file_operations_summary()
    
    # 清理创建的文件
    import os
    try:
        os.remove("example.txt")
        os.remove("employees.csv")
        print("\n已清理临时文件")
    except:
        pass